package com.yc.mypredicatefactory;

import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;

@Component
public class DeviceRoutePredicateFactory extends AbstractRoutePredicateFactory<DeviceRoutePredicateFactory.Config> {

    public DeviceRoutePredicateFactory() {
        super(Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Collections.singletonList("deviceType"); // 支持配置 deviceType=PC|Mobile
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return exchange -> {
            String userAgent = exchange.getRequest().getHeaders().getFirst("User-Agent");
            if (userAgent == null) return false;

            String ua = userAgent.toLowerCase();

            // 判断是否为手机设备
            boolean isMobile = ua.contains("iphone") || ua.contains("android") || ua.contains("mobile");

            if ("Mobile".equalsIgnoreCase(config.getDeviceType())) {
                return isMobile;
            } else if ("PC".equalsIgnoreCase(config.getDeviceType())) {
                return !isMobile;
            }

            return false;
        };
    }

    public static class Config {
        private String deviceType;

        public String getDeviceType() {
            return deviceType;
        }

        public void setDeviceType(String deviceType) {
            this.deviceType = deviceType;
        }
    }
}
